<?php
/**
 * User 模型类
 * 
 */

class User_model extends CI_Model {

    public function __construct()
    {
        $this->load->database();
    }

    // 用户注册
    function add_user($username, $password, $email)
    {
        $data = array(
            'username'=>$username,
            'password'=>$password,
            'email'=>$email
        );

        $this->db->insert('user', $data);

        if ($this->db->affected_rows() > 0)
        {
             $this->login($username);
             return TRUE;
        }

        return FALSE;
    }

    // 用户登录(添加session数据)
    function login($username)
    {
        $data = array('username'=>$username, 'logged_in'=>TRUE);
        $this->session->set_userdata($data);
    }

    // 检查用户名是否被使用
    function get_by_username($username)
    {
        $this->db->where('username', $username);
        $query = $this->db->get('user');

        return $query->num_rows() ? TRUE : FALSE;
    }

    // 检查邮箱是否被使用
    function email_exists($email)
    {
        $this->db->where('email', $email);
        $query = $this->db->get('user');
        return $query->num_rows() ? TRUE : FALSE;
    }

    // 检查登录密码
    function password_check($username, $password)
    {
        $this->db->where('username', $username);
        $query = $this->db->get('user');

        if($query->num_rows() > 0)
        {
            $row =  $query->row_array();
            return ($row['password'] == $password) ? TRUE : FALSE;
        }
        else
        {
            return FALSE;
        }
    }



}
